package org.ufinity.hsms.common.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import static org.ufinity.hsms.common.tool.logs.Logs.d;
import static org.ufinity.hsms.common.tool.logs.Logs.e;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import org.apache.commons.codec.binary.Base64;

/**
 * @Description 文件读写
 * @author 钱新才
 * @version 1.0 2011-10-21
 * @class com.tydic.weibo.module.commmon.FileUtils
 */
public class FileUtils {

	private static final String TAG = "FileUtils";

	/**
	 * 写文本文件 在Android系统中，文件保存在 /data/data/PACKAGE_NAME/files 目录下
	 * 
	 * @param context
	 * @param msg
	 */
	public static void write(Context context, String fileName, String content) {
		if (content == null) {
			content = "";
		}

		try {
			FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
			fos.write(content.getBytes());

			fos.close();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 读取文本文件
	 * 
	 * @param context
	 * @param fileName
	 * @return
	 */
	public static String read(Context context, String fileName) {
		try {
			FileInputStream in = context.openFileInput(fileName);
			return readInStream(in);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	private static String readInStream(FileInputStream inStream) {
		try {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buffer = new byte[512];
			int length = -1;
			while ((length = inStream.read(buffer)) != -1) {
				outStream.write(buffer, 0, length);
			}

			outStream.close();
			inStream.close();
			return outStream.toString();
		}
		catch (IOException ex) {
			if (ex != null) {
				e(TAG, ex.getMessage());
			}
		}
		return null;
	}

	public static File createFile(String folderPath, String fileName) {
		File destDir = new File(folderPath);
		if (!destDir.exists()) {
			destDir.mkdirs();
		}
		return new File(folderPath, fileName + fileName);
	}

	/**
	 * 根据路径创建文件夹
	 * 
	 * @param path
	 * @return
	 */
	public static String creatFolder(String path) {
		File folder = new File(path);
		if (!folder.exists()) {
			folder.mkdirs();
		}
		return path;
	}

	/**
	 * 向手机写图片
	 * 
	 * @param buffer
	 * @param folder
	 * @param fileName
	 * @return
	 */
	public static boolean writeFile(byte[] buffer, String folder, String fileName) {
		boolean writeSucc = false;

		boolean sdCardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);

		String folderPath = "";
		if (sdCardExist) {
			folderPath = Environment.getExternalStorageDirectory() + File.separator + folder + File.separator;
		}
		else {
			writeSucc = false;
		}

		File fileDir = new File(folderPath);
		if (!fileDir.exists()) {
			fileDir.mkdirs();
		}

		File file = new File(folderPath + fileName);
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file);
			out.write(buffer);
			writeSucc = true;
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		finally {
			try {
				out.close();
			}
			catch (IOException e) {
				e.printStackTrace();
			}
		}

		return writeSucc;
	}

	/**
	 * 根据文件绝对路径获取文件名
	 * 
	 * @param filePath
	 * @return
	 */
	public static String getFileName(String filePath) {
		if (StringUtils.isBlank(filePath)) {
			return "";
		}
		return filePath.substring(filePath.lastIndexOf(File.separator) + 1);
	}

	/**
	 * 根据文件的绝对路径获取文件名但不包含扩展名
	 * 
	 * @param filePath
	 * @return
	 */
	public static String getFileNameNoFormat(String filePath) {
		if (StringUtils.isBlank(filePath)) {
			return "";
		}
		int point = filePath.lastIndexOf('.');
		return filePath.substring(filePath.lastIndexOf(File.separator) + 1, point);
	}

	/**
	 * 获取文件扩展名
	 * 
	 * @param fileName
	 * @return
	 */
	public static String getFileFormat(String fileName) {
		if (StringUtils.isBlank(fileName)) {
			return "";
		}

		int point = fileName.lastIndexOf('.');
		return fileName.substring(point + 1);
	}

	/**
	 * 获取文件大小
	 * 
	 * @param filePath
	 * @return
	 */
	public static long getFileSize(String filePath) {
		long size = 0;

		File file = new File(filePath);
		if (file != null && file.exists()) {
			size = file.length();
		}
		return size;
	}

	/**
	 * 获取文件大小
	 * 
	 * @param size
	 *        字节
	 * @return
	 */
	public static String getFileSize(long size) {
		if (size <= 0) {
			return "0";
		}
		java.text.DecimalFormat df = new java.text.DecimalFormat("##.##");
		float temp = (float) size / 1024;
		if (temp >= 1024) {
			return df.format(temp / 1024) + "M";
		}
		else {
			return df.format(temp) + "K";
		}
	}

	public static byte[] toBytes(InputStream in) throws IOException {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int ch;
		while ((ch = in.read()) != -1) {
			out.write(ch);
		}
		byte buffer[] = out.toByteArray();
		out.close();
		return buffer;
	}

	/**
	 * 设置图片大小限制为0.1M
	 */
	public static final long IMGSIZE = (1024 * 1024) / 10;

	/**
	 * 等比压缩处理
	 * 
	 * @Description
	 * @param oldFile
	 * @return
	 * @author 钱新才
	 * @version 1.0 2011-11-9
	 */
	public static File reSiteImgFile(String filePath) {

		File oldFile = new File(filePath);
		int be = (int) (oldFile.length() / (float) IMGSIZE);
		/**
		 * <=1的压缩二分之一
		 */
		if (be <= 1) {
			be = 2;
		}

		d(TAG, "图片压缩比例:" + be);

		BitmapFactory.Options opts = new BitmapFactory.Options();
		opts.inSampleSize = be;
		// 重新读入图片，注意这次要把options.inJustDecodeBounds 设为 false
		// opts.inJustDecodeBounds=false;
		Bitmap bitmap = BitmapFactory.decodeFile(filePath, opts);

		String camerName = InfoHelper.getFileName();
		String fileName = "wo_weibo_" + camerName + ".jpg";
		// 创建图片存储路径文件夹
		String imgFolder = InfoHelper.createWoWeiboAndFolder(InfoHelper.getTmpPath());

		String path = imgFolder + fileName;

		File file = new File(path);
		try {
			FileOutputStream out = new FileOutputStream(file);
			if (bitmap.compress(Bitmap.CompressFormat.PNG, 100, out)) {
				out.flush();
				out.close();
			}
			d(TAG, "test:" + file.getName());
			return file;

		}
		catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 将文件编码成base64格式
	 * 
	 * @param image
	 * @return
	 * @throws IOException
	 */
	public static String encodeFile(File file) throws IOException {
		InputStream is = null;
		try {
			is = new FileInputStream(file);
			byte[] bytes = getBytesFromStream(is);
			byte[] encoded = Base64.encodeBase64(bytes);
			String fileBase64 = new String(encoded, "utf-8");
			return fileBase64;
		}
		finally {
			if (is != null) {
				is.close();
			}
		}
	}

	/**
	 * 将输入流转化成字节数组
	 * 
	 * @param inputStream
	 * @return
	 * @throws IOException
	 */
	public static byte[] getBytesFromStream(InputStream is) throws IOException {
		byte[] data = null;

		Collection chunks = new ArrayList();
		byte[] buffer = new byte[1024 * 1000];
		int read = -1;
		int size = 0;

		while ((read = is.read(buffer)) != -1) {
			if (read > 0) {
				byte[] chunk = new byte[read];
				System.arraycopy(buffer, 0, chunk, 0, read);
				chunks.add(chunk);
				size += chunk.length;
			}
		}
		if (size > 0) {
			ByteArrayOutputStream bos = null;
			try {
				bos = new ByteArrayOutputStream(size);
				for (Iterator itr = chunks.iterator(); itr.hasNext();) {
					byte[] chunk = (byte[]) itr.next();
					bos.write(chunk);
				}
				data = bos.toByteArray();
			}
			finally {
				if (is != null) {
					is.close();
				}
				if (bos != null) {
					bos.flush();
					bos.close();
				}
			}
		}
		return data;
	}

	public String getStringByBytes(byte[] bytes) {
		String str = new String(bytes);
		return str;
	}
}